<!-- 推广中心 通用列表模板 -->
<template>
  <div id="base-reward-template">
    <c-title :hide="false" :text="diy_name"></c-title>
    <div class="headTop" v-if="info.member">
      <div class="himg">
        <img :src="info.member && info.member.avatar" alt="" />
      </div>
      <div class="userBox">
        <div class="name">{{ info.member && info.member.nickname }}</div>
        <div>
          <div class="grade" v-if="info.member && info.member.level_name">{{ info.member.level_name }}</div>
        </div>
      </div>
      <!-- 年月选择按钮，默认当前年月 -->
      <div v-if="datetime" class="grade m-0 bg-fff-o f-15" @click.stop="clickDatetime">{{ currentDateValue || "筛选时间" }}<i class="iconfont icon-down"></i></div>
    </div>
    <div class="number_List" :style="{ marginTop: info.member ? '-2.75rem' : '1rem' }">
      <!-- 数据标题 -->
      <template v-if="info.statisticTitle">
        <div class="headTitle" v-for="(item, ind) in info.statisticTitle" :key="ind" :style="statisticTitle_Style(item.node)">
          <div class="span" :style="statisticTitle_Style(item.title_node)">{{ item.title }}</div>
          <div class="top" :style="statisticTitle_Style(item.value_node)">
            <template v-if="item.isPrice">￥</template>
            {{ item.value }}
          </div>
        </div>
      </template>
      <!--  数据分列，只有一个时横排显示 -->
      <template v-if="info.statistic && info.statistic.length > 1">
        <div class="lis" v-for="(item, i) in info.statistic" :key="i" :style="{'max-width': info.statistic.length > 2?'33%':'none'}">
          <div class="top"><template v-if="item.isPrice">￥</template>{{ item.value }}</div>
          <div class="txt">{{ item.name }}</div>
        </div>
      </template>
      <template v-else-if="info.statistic && info.statistic.length === 1">
        <div class="lis flex-j-sb" v-for="(item, i) in info.statistic" :key="i" style="margin: 0.875rem;">
          <div class="txt">{{ item.name }}</div>
          <div class="top" style="margin: 0;"><template v-if="item.isPrice">￥</template>{{ item.value }}</div>
        </div>
      </template>
    </div>
    <!--  数据end -->
    <!--  选项卡 -->
    <div class="navList" :class="[!info.member && !info.statistic ? 'no_lr_margin' : '', info.tabClass]">
      <van-tabs v-model="activeName" @change="handleClick" :title-active-color="'#F15353'" :color="'#F15353'" sticky swipeable :ellipsis="false">
        <van-tab :title="items.name" v-for="(items, ind) in titleArr" :key="ind">
          <!-- 搜索框 dataList[ind].search.name-->
          <van-search
            v-if="titleArr[ind].search"
            v-model="titleArr[ind].search.name"
            :placeholder="titleArr[ind].search.placeholder || '请输入搜索'"
            @search="onSearch"
            @input="onInputSearch"
            @clear="onClearSearch"
          />
          <!-- 搜索框 end-->
          <!-- 下拉菜单 -->
          <van-sticky :offset-top="44">
            <van-dropdown-menu v-if="titleArr[ind].dropdown">
              <van-dropdown-item @change="onSearch" v-for="(dropdownItem,dropdownIndex) in titleArr[ind].dropdown" v-model="dropdownItem.value" :options="dropdownItem.option" :key="dropdownIndex"/>
            </van-dropdown-menu>
          </van-sticky>
          <!-- 下拉菜单 end  -->
          <div v-if="dataList[ind] && !fun.isTextEmpty(dataList[ind].list)">
            <div class="lis" v-for="(item, index) in dataList[ind].list" :key="index">
              <div class="rwo" v-for="col in items.nodeKey" :key="col.key" @click.stop="clickCol(item)">
                <template v-if="!col.class">
                  <div
                    class="col"
                    :class="[ci % 2 === 0 ? 't-l' : 't-r', node.class, node.avatarImage ? 'flex' : '']"
                    v-for="(node, ci) in col.node"
                    :key="node.key"
                    :style="{
                      color: (node.type && (node.type == 'changeVal' && fun.getDeepJsonValue(item, node.key) > 0 ? '#f15353' : '#259b24')) || node.color || '#818181',
                      fontSize: node.size || '12px'
                    }"
                  >
                    <template v-if="node.leftText">{{ node.leftText }}</template>
                    <template v-if="node.avatarImage">
                      <img class="min-img" :src="fun.getDeepJsonValue(item, node.avatarImage)" alt="" />
                    </template>
                    <template v-if="node.isPrice">￥</template>{{ fun.getDeepJsonValue(item, node.key) }}
                    <template v-if="node.rightText">{{ node.leftText }}</template>
                  </div>
                </template>
                <template v-else>
                  <div class="number_List" style="margin: 0;width: 100%;">
                    <div class="lis" v-for="(node, i) in col.node" :key="i" style="margin: 0;border: none;">
                      <div class="top" :style="{ color: node.color || '#999', fontSize: node.size || '12px' }">
                        <template v-if="node.leftText">{{ node.leftText }}</template
                        ><template v-if="node.isPrice">￥</template>{{ fun.getDeepJsonValue(item, node.key) }}<template v-if="node.rightText">{{ node.leftText }}</template>
                      </div>
                      <div class="txt" v-if="node.key_2">{{ fun.getDeepJsonValue(item, node.key_2) }}</div>
                    </div>
                  </div>
                </template>
              </div>
            </div>
          </div>
        </van-tab>
      </van-tabs>
    </div>
    <div v-if="finished" style="color: #999;padding-bottom:1rem;">没有更多~</div>

    <!-- 年月选择器 -->
    <van-popup v-model="showDatetime" position="bottom" round>
      <van-datetime-picker v-model="currentDate" type="year-month" title="选择年月" cancel-button-text="清除" :min-date="minDate" :max-date="maxDate" @confirm="setDateTime" @cancel="clearDateTime" />
    </van-popup>
  </div>
</template>
<script>
import { scrollMixin } from "utils/mixin";
export default {
  mixins: [scrollMixin], //加载更多
  data() {
    return {
      api: "",
      activeName: 0,
      info: [],
      titleArr: [],
      dataList: [],
      diy_name: "--",
      finished: false,
      isLoadMore: true,

      minDate: new Date(2015, 0, 1),
      maxDate: new Date(),
      currentDate: new Date(),
      currentDateValue: new Date().Format("yyyy-MM"),
      showDatetime: false,
      datetime: false //是否显示年月选择
    };
  },
  activated() {
    this.init();
    this.getData();
  },
  computed: {
    statisticTitle_Style(node) {
      return function(node) {
        if (node) {
          return node;
        } else {
          return {
            color: "#000",
            fontSize: "18px",
            fontWeight: "600",
            textAlign: "left"
          };
        }
      };
    }
  },
  methods: {
    init() {
      if (!this.$route.query.api) {
        return this.$toast("缺少必要参数");
      }
      this.dataList = [];
      this.titleArr = [];
      this.isLoadMore = true;

      if (this.$route.query.date_time && this.$route.query.date_time == 1) {
        this.datetime = true;
      }
    },
    initList() {
      this.dataList[this.activeName].list = [];
      this.dataList[this.activeName].page = 1;
      this.dataList[this.activeName].isLoadMore = true;
    },
    async getData() {
      let _parame = this.$route.query.extparams ? JSON.parse(this.$route.query.extparams) : {};
      if (this.datetime && this.currentDateValue) {
        _parame = { ..._parame, datetime: this.currentDateValue }; //开启了年月筛选
      }
      let { msg, result, data } = await $http.get(this.$route.query.api, _parame, ".");
      if (result == 0) {
        return this.$toast(msg);
      }

      let { tabArr, page_title, ...other } = data;
      this.info = other;
      // tabArr[0].nodeKey[0].node[1].type = 'changeVal';

      // tabArr[1].dropdown = [{
      //   value: 0,
      //   name: 'rewards_type',
      //   option: [
      //     { text: '全部', value: -1 },
      //     { text: '收入', value: 0 },
      //     { text: '探币', value: 1 }
      //   ]
      // },{
      //   value: 'b',
      //   name: 'name',
      //   option: [
      //     { text: '默认排序', value: 'a' },
      //     { text: '好评排序', value: 'b' },
      //     { text: '销量排序', value: 'c' }
      //   ]
      // }
      // ];

      // tabArr[0].search = {
      //   placeholder: "搜索证书",
      //   queryString: "certificate_no",
      //   name: null
      // };

      // tabArr[0].handle = {
      //   type : "navigateTo",
      //   routerName : 'consumptionGiftDetail',
      //   mini_url : '小程序的页面路径',
      //   paramsKey : ['id'],
      //   paramName : ['id'],
      //   queryKey : [],
      //   queryName : []
      // };

      this.titleArr = tabArr;
      this.diy_name = page_title;
      this.fun.setWXTitle(this.diy_name);
      this.setNewArr();
    },
    setNewArr() {
      this.titleArr.forEach((val, index) => {
        this.dataList.push({
          isLoadMore: true,
          page: 1,
          total_page: 0,
          list: [],
          url: val.url,
          extParameter: val.extParameter
        });
      });
      this.handleClick();
    },
    handleClick() {
      if (!this.fun.isTextEmpty(this.dataList[this.activeName].list)) {
        this.isLoadMore = this.dataList[this.activeName].isLoadMore;
        return;
      }
      let _parameter1 = { page: 1 };
      let _parameter2 = this.dataList[this.activeName]?.extParameter || {};
      this.parameter = { ..._parameter1, ..._parameter2 };
      if (this.titleArr[this.activeName].search) {
        // 开启搜索框
        this.parameter[this.titleArr[this.activeName].search.queryString] = this.titleArr[this.activeName].search.name;
      }
      if (this.titleArr[this.activeName].dropdown) {
        // 开启菜单下拉框
        this.titleArr[this.activeName].dropdown.forEach(item => {
          this.parameter[item.name] = item.value;
        });
      }
      if (this.datetime && this.currentDateValue) {
        this.parameter.datetime = this.currentDateValue; //开启了年月筛选
      }

      $http
        .post(this.dataList[this.activeName].url, this.parameter, "")
        .then(response => {
          if (response.result === 1) {
            this.isLoadMore = true;
            this.dataList[this.activeName].isLoadMore = true;
            this.dataList[this.activeName].total_page = response.data.last_page;

            if (!this.dataList[this.activeName].total_page) {
              this.dataList[this.activeName].total_page = 0;
            }
            this.dataList[this.activeName].list = response.data.data;
            this.$nextTick(() => {
              this.$set(this.dataList[this.activeName], "list", response.data.data);
            });
            if (response.data.data.length === 0) this.finished = true;
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    //获取更多数据
    getMoreData() {
      if (!this.dataList[this.activeName]) return;
      this.dataList[this.activeName].isLoadMore = false;
      this.isLoadMore = false; // 防止多次请求分页数据
      if (this.dataList[this.activeName].page >= this.dataList[this.activeName].total_page) {
        this.finished = true;
        return;
      } else {
        this.dataList[this.activeName].page = this.dataList[this.activeName].page + 1;
        let _parameter1 = { page: this.dataList[this.activeName].page };
        let _parameter2 = this.dataList[this.activeName]?.extParameter || {};
        this.parameter = { ..._parameter1, ..._parameter2 };

        if (this.titleArr[this.activeName].search) {
          // 开启搜索框
          this.parameter[this.titleArr[this.activeName].search.queryString] = this.titleArr[this.activeName].search.name;
        }
        if (this.titleArr[this.activeName].dropdown) {
          // 开启菜单下拉框
          this.titleArr[this.activeName].dropdown.forEach(item => {
            this.parameter[item.name] = item.value;
          });
        }
        if (this.datetime) {
          this.parameter.datetime = this.currentDateValue; //开启了年月筛选
        }

        $http.get(this.dataList[this.activeName].url, this.parameter, "加载中").then(
          response => {
            this.isLoadMore = true;
            this.dataList[this.activeName].isLoadMore = true;
            if (response.result === 1) {
              var myData = response.data.data;
              this.dataList[this.activeName].list = this.dataList[this.activeName].list.concat(myData); //数组拼接
            } else {
              this.dataList[this.activeName].page = this.dataList[this.activeName].page - 1;
              this.dataList[this.activeName].isLoadMore = false;
              this.isLoadMore = false;
            }
          },
          function(response) {
            // error callback
          }
        );
      }
    },
    // 搜索框逻辑 --------------
    onInputSearch(e) {
      this.$set(this.titleArr[this.activeName].search, "name", e);
    },
    onSearch() {
      this.initList();
      this.handleClick();
    },
    onClearSearch() {
      this.parameter[this.titleArr[this.activeName].search.queryString] = "";
      this.$set(this.titleArr[this.activeName].search, "name", "");
    },
    // 搜索框逻辑 end  --------------
    // 列表点击事件 逻辑 --------------
    clickCol(data) {
      let { type, ...navigateData } = this.titleArr[this.activeName]?.handle || {};
      if (type && type === "navigateTo") {
        this.navigateToPage(data, navigateData); //点击跳转页面
      }
      // 其他 type ....
    },
    navigateToPage(data, navigateData) {
      let paramsData = {};
      let queryData = {};
      let { paramsKey, paramName, queryKey, queryName, routerName } = navigateData;
      // 构建paramsData，用于router跳转时params传参
      for (let i = 0; i < paramsKey.length; i++) {
        let key = paramsKey[i];
        let name = paramName[i];
        paramsData[name] = data[key];
      }

      // 构建queryData，用于router跳转时query传参
      for (let i = 0; i < queryKey.length; i++) {
        let key = queryKey[i];
        let name = queryName[i];
        queryData[name] = data[key];
      }
      console.log(paramsData);
      console.log(queryData);

      this.$router.push(this.fun.getUrl(routerName, paramsData, queryData));
    },
    // 列表点击事件 end --------------
    clickDatetime() {
      this.showDatetime = true;
    },
    setDateTime(ret) {
      this.currentDateValue = ret.Format("yyyy-MM");
      this.showDatetime = false;
      this.init();
      this.getData();
    },
    clearDateTime() {
      this.currentDateValue = "";
      this.showDatetime = false;
      this.init();
      this.getData();
    }
  }
};
</script>
<style lang="scss" scoped>
.m-0 {
  margin: 0;
}
.f-15 {
  font-size: 0.9375rem;
}
.bg-fff-o {
  background: rgba(255, 255, 255, 0.3);
}

.headTop {
  padding: 1.5rem 0.75rem 2.875rem;
  margin-bottom: 1rem;
  background: linear-gradient(var(--themeBaseColor), #f5f5f5);
  display: flex;
  align-items: center;
  .userBox {
    display: flex;
    flex-direction: column;
    margin-left: 0.41rem;
    text-align: left;
    flex: 1;
    .name {
      font-size: 1rem;
      color: #ffffff;
      font-weight: bold;
    }
  }
  .grade {
    display: inline-block;
    padding: 0.25rem 0.625rem;
    border-radius: 0.9rem;
    color: #ffffff;
    margin-top: 0.375rem;
    font-size: 0.75rem;
    background: rgba(0, 0, 0, 0.1);
    text-align: center;
    min-width: 4rem;
  }

  .himg {
    width: 3.44rem;
    height: 3.44rem;
    border-radius: 100%;
    img {
      width: 100%;
      height: 100%;
      border-radius: 100%;
    }
  }
}
.navList {
  margin: 0 0.75rem 1rem;
  border-radius: 0.31rem;
  background: #ffffff;
  overflow: hidden;
  box-sizing: border-box;
  .lis {
    padding: 0.5rem;
    margin: 0 0.25rem;
    border-bottom: 1px solid #f2f2f2;
    .rwo {
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;
      .col {
        // flex-shrink: 0;
        line-height: 1.375rem;
        flex: 1 1 50%;
        // width: 50%;
        font-size: 0.75rem;
        color: #999999;
        white-space: nowrap;
      }
    }
    .rwo:last-child {
      margin-bottom: 0;
    }
  }
}

.min-img {
  width: 1.25rem;
  height: 1.25rem;
  border-radius: 50%;
  flex-shrink: 0;
  display: flex;
  margin: 0 0.25rem 0 0;
}

.navlist-radius-block {
  background: #f5f5f5;
  .lis {
    margin: 0.75rem;
    border-radius: 0.75rem;
    padding: 0.75rem;
    background: #ffffff;
  }
}

.t-l {
  text-align: left;
}
.t-r {
  text-align: right;
  flex: 1 !important;
}
.bold {
  font-weight: bold !important;
}
// .price {
//   color: #f15353 !important;
//   font-size: 0.875rem !important;
// }
.number_List {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin: -2.75rem 0.75rem 1rem;
  background: #ffffff;
  border-radius: 0.31rem;
  flex-wrap: wrap;
  .headTitle {
    flex-shrink: 0;
    width: 100%;
    display: flex;
    padding: 0.5rem 1rem;
  }
  .lis {
    flex: 1;
    margin: 1rem 0;
    min-width: 33%;
    .top {
      font-size: 0.88rem;
      color: #3b3b4a;
      margin-bottom: 0.375rem;
      font-weight: bold;
    }
    .txt {
      color: #aaaab3;
      font-size: 0.75rem;
    }
  }
  .lis_right {
    border-right: 1px solid #e7e7e7;
  }
  .lis:last-child {
    border-right: 0;
  }
}

.no_lr_margin {
  margin: 0 0 1rem;
}

.van-dropdown-menu ::v-deep.van-dropdown-menu__bar {
  box-shadow: 0 6px 8px rgba(100,101,102,.12);
}
</style>
